package com.itheima.mpermission.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mpermission.config.RsaKeyProperties;
import com.itheima.mpermission.domain.SysRole;
import com.itheima.mpermission.domain.SysUser;
import com.itheima.mpermission.dto.PermissionAutoDTO;
import com.itheima.mpermission.dto.PermissionDTO;
import com.itheima.mpermission.dto.RepPermission;
import com.itheima.mpermission.dto.SubpermissionDTO;
import com.itheima.mpermission.mapper.PermissionMapper;
import com.itheima.mpermission.pojo.Permission;
import com.leyou.common.auth.domain.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class  PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RsaKeyProperties prop;

    public List<PermissionAutoDTO> findAll() {

        List<PermissionAutoDTO> permissionDTOList = new ArrayList<>();

        Example example = new Example(Permission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isParent",true);
        //查询父目录
        List<Permission> parentList = permissionMapper.selectByExample(example);
        //获取父目录的id
        List<Long> parentIds = parentList.stream().map(Permission::getParentId).collect(Collectors.toList());
        //查询所有子目录
        List<Permission> subPermissions = permissionMapper.selectByIdList(parentIds);
        //遍历父目录
        parentList.forEach(permission -> {
            PermissionAutoDTO permissionDTO = new PermissionAutoDTO();
            permissionDTO.setTitle(permission.getChildrenName());
            permissionDTO.setPath(permission.getChildrenPath());
            permissionDTO.setId(permission.getId());

            List<Map<String, String>> items=new ArrayList<>();
            //遍历子目录，获取该父目录下对应的子目录
            for(Permission subpermission:subPermissions){
                if(subpermission.getParentId().equals(permission.getId())){
                    Map<String,String> map=new HashMap<>();
                    map.put("title",subpermission.getChildrenName());
                    map.put("path",subpermission.getChildrenPath());
                    items.add(map);
                }
            }
            permissionDTO.setItems(items);

            permissionDTOList.add(permissionDTO);
        });
        return permissionDTOList;
    }

    public List<PermissionAutoDTO> findByRoles(HttpServletRequest request) {

        List<PermissionAutoDTO> permissionDTOList = new ArrayList<>();
        //根据当前用户的角色获取相对应的权限
        List<Permission> permissions = getPermissions(request);


        List<Permission> prePermission=new ArrayList<>();
        List<Permission> subPermission=new ArrayList<>();

        for (Permission permission : permissions) {
            if(permission.getIsParent()){
                prePermission.add(permission);
                continue;
            }
            subPermission.add(permission);
        }

        for (Permission permission : prePermission) {
            PermissionAutoDTO permissionDTO=new PermissionAutoDTO();
            permissionDTO.setId(permission.getId());
            permissionDTO.setPath(permission.getChildrenPath());
            permissionDTO.setTitle(permission.getChildrenName());

            List<Map<String, String>> items=new ArrayList<>();

            for (Permission subPer : subPermission) {
                Map<String,String> map=new HashMap<>();
                if(subPer.getParentId().equals(permission.getId())){
                    map.put("title",subPer.getChildrenName());
                    map.put("path",subPer.getChildrenPath());
                    items.add(map);
                }
            }
            permissionDTO.setItems(items);
            permissionDTOList.add(permissionDTO);
        }
        return permissionDTOList;
    }



    public List<SubpermissionDTO> findSubPath(HttpServletRequest request) {
        //创建一个集合返回
        List<SubpermissionDTO> subPathList=new ArrayList<>();
        //根据当前用户的角色获取相对应的权限
        List<Permission> permissions = getPermissions(request);

        List<Permission> subPermission=new ArrayList<>();

        permissions.forEach(permission -> {
            if(permission.getParentPath()!=null){
                subPermission.add(permission);
            }
        });

        subPermission.forEach(permission -> {
            SubpermissionDTO subpermissionDTO=new SubpermissionDTO();
            subpermissionDTO.setChildrenPath(permission.getChildrenPath());
            subpermissionDTO.setParentPath(permission.getParentPath());
            subPathList.add(subpermissionDTO);
        });


           return subPathList;
        }


    /**
     * 分页排序 搜索查询
     * @param page 当前页
     * @param rows 每页的行数
     * @return
     */
    public PageResult<PermissionDTO> queryListByPage(Integer page, Integer rows) {
        //分页
        PageHelper.startPage(page,rows);
        //查询用户
        List<Permission> permissions = permissionMapper.selectAll();
        //解析分页结果
        PageInfo<Permission> pageInfo = new PageInfo<>(permissions);
        //将对象转换成DTO
        List<PermissionDTO> permissionDTOS = BeanHelper.copyWithCollection(permissions, PermissionDTO.class);
        //返回
        return new PageResult<>(pageInfo.getTotal(),permissionDTOS);
    }

    //根据
    public List<PermissionDTO> findPermissionByParentId(Long pid) {
        Permission record = new Permission();
        record.setParentId(pid);
        List<Permission> permissionList = permissionMapper.select(record);
        if (CollectionUtils.isEmpty(permissionList)){
            throw new LyException(503,"权限不存在！");
        }
        return BeanHelper.copyWithCollection(permissionList,PermissionDTO.class);
    }

    public List<PermissionDTO> findPermissionById(Long pid) {
        List<Permission> permissions = permissionMapper.selectPermission(pid);
        if (CollectionUtils.isEmpty(permissions)){
            throw new LyException(503,"权限不存在！");
        }
        return BeanHelper.copyWithCollection(permissions,PermissionDTO.class);
    }




    //根据当前用户的角色获取相对应的权限
    private List<Permission> getPermissions(HttpServletRequest request) {
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());

        if(token==null){
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_SIGN);
        }

        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);

        SysUser user = payload.getUserInfo();

        List<SysRole> sysRoles = (List<SysRole>) user.getAuthorities();

        List<Integer> roleIds = sysRoles.stream().map(SysRole::getId).collect(Collectors.toList());

        return permissionMapper.selectByRoleIds(roleIds);
    }

    //添加权限
    public void addPermission(RepPermission repPermission) {
        try {
            PermissionDTO permission = repPermission.getPermission();

            if(permission.getId()==21){
                Permission record=new Permission();
                record.setChildrenName(repPermission.getChildrenName());
                record.setChildrenPath(repPermission.getChildrenPath());
                record.setParentId(0l);
                record.setIsParent(true);
                permissionMapper.insertSelective(record);

            }else {

                Permission record = new Permission();
                record.setParentId(permission.getId());
                Permission Prepermission = permissionMapper.selectByPrimaryKey(permission.getId());
                record.setParentPath(Prepermission.getChildrenPath());
                record.setIsParent(false);
                record.setParentName(permission.getChildrenName());
                record.setChildrenName(repPermission.getChildrenName());
                record.setChildrenPath(repPermission.getChildrenPath());

                permissionMapper.insertSelective(record);
            }
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    //修改权限
    public void updatePermission(RepPermission repPermission) {
        int count = permissionMapper.deleteByPrimaryKey(repPermission.getId());
        if (count != 1) {
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
        Permission record=new Permission();
        record.setChildrenName(repPermission.getChildrenName());
        record.setChildrenPath(repPermission.getChildrenPath());
        //根据权限id查询对象
        Permission permission = permissionMapper.selectByPrimaryKey(repPermission.getPermission().getId());
        record.setParentName(permission.getChildrenName());
        record.setParentPath(permission.getChildrenPath());
        record.setParentId(permission.getId());
        record.setIsParent(repPermission.getIsParent());
        //执行添加操作
        permissionMapper.insert(record);
    }

    public void deletePermission(Long id) {
        int count = permissionMapper.deleteByPrimaryKey(id);
        if(count!=1){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }
}
